package com.hbnu.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hbnu.system.config.BaseException;
import com.hbnu.system.constant.AuthorTypeConstants;
import com.hbnu.system.mapper.AwardauthorMapper;
import com.hbnu.system.model.entity.Award;
import com.hbnu.system.model.entity.Award_Qualification;
import com.hbnu.system.model.entity.Awardauthor;
import com.hbnu.system.model.entity.User;
import com.hbnu.system.service.IAwardQualificationService;
import com.hbnu.system.service.IAwardService;
import com.hbnu.system.service.IAwardauthorService;
import com.hbnu.system.service.IUserService;
import com.hbnu.system.utils.CheckRoleUtil;
import com.hbnu.system.utils.IdGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 奖励成果作者服务实现类
 * </p>
 *
 * @author ${jxl}
 * @since 2023-05-16
 */
@Service
public class AwardauthorServiceImpl extends ServiceImpl<AwardauthorMapper, Awardauthor> implements IAwardauthorService {

    @Autowired
    private IAwardauthorService iAwardauthorService;

    @Autowired
    private IAwardService iAwardService;

    @Autowired
    private IUserService iUserService;

    @Autowired
    private CheckRoleUtil checkRoleUtil;
    
    @Autowired
    private IAwardQualificationService iAwardQualificationService;

    private static final List<String> AUTHOR_TYPE_ORDER = Arrays.asList(
            "第一作者", "共同第一作者", "通讯作者", "第二作者", "第三作者", "其他排名"
    );

    private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("0.00");
    
    /**
     * 添加奖励成果作者
     * @param awardAuthor
     * @return
     */
    @Override
    public boolean addAwardAuthor(Awardauthor awardAuthor) {
        // 不使用前端传过来的id，而是生成一个新的id
        awardAuthor.setAwardAuthorID(null);
        Award award = iAwardService.query().eq("AwardID", awardAuthor.getAwardID()).one();
        checkRoleUtil.checkPermissionAchievement(award.getStatus());

        //如果是校外作者或者学生，为其生成工号
        if (awardAuthor.getPeopleType().equals(AuthorTypeConstants.OUT_SCHOOL_AUTHOR)
                ||awardAuthor.getPeopleType().equals(AuthorTypeConstants.STUDENT)) {
            awardAuthor.setUserAccount(IdGenerator.generateId());
        }

        if (awardAuthor.getUserAccount().isEmpty()) {
            throw new BaseException("请输入工号");
        }

        Awardauthor pa1 = iAwardauthorService.getOne(Wrappers.lambdaQuery(Awardauthor.class)
                .eq(Awardauthor::getAwardID, awardAuthor.getAwardID())
                .eq(Awardauthor::getUserAccount, awardAuthor.getUserAccount()));
        if (Objects.nonNull(pa1)) {
            throw new BaseException("不可重复添加");
        }
        if (StrUtil.isBlank(awardAuthor.getAssessment())) {
            throw new BaseException("请输入考核系数");
        }

        double newAssessment;
        try {
            String assessment = awardAuthor.getAssessment();
            // 如果考核系数为null或空，默认为0
            if (assessment == null || assessment.trim().isEmpty()) {
                newAssessment = 0.0;
            } else {
                newAssessment = Double.parseDouble(assessment);
            }
        } catch (NumberFormatException e) {
            throw new BaseException("考核系数格式不正确");
        }
        if (newAssessment > 100 || newAssessment < 0) {
            throw new BaseException("输入数据应在0-100范围内");
        }

        // 判断加起来总分是否超过100
        List<Awardauthor> awardAuthorList = iAwardauthorService.listAuthor(awardAuthor.getAwardID());
        double sum = 0;
        for (Awardauthor author : awardAuthorList) {
            if(author.getAssessment().equals("")){
                throw new BaseException("请补全所有作者考核系数");
            }
            sum += Double.parseDouble(author.getAssessment());
        }
        if (sum + newAssessment > 100) {
            throw new BaseException("作者考核系数总和大于100!");
        }

        String Pscore = "0.00";

        LambdaQueryWrapper<Award_Qualification> wrapper = Wrappers.lambdaQuery(Award_Qualification.class)
                .eq(Award_Qualification::getAwardID, awardAuthor.getAwardID());
        Award_Qualification awardQualification= iAwardQualificationService.getOne(wrapper);

        if(awardQualification != null){
            int finalValue = (int) awardQualification.getFinalValue();
            // 计算并保留两位小数
            double pscore = finalValue * newAssessment / 100.0;
            Pscore = DECIMAL_FORMAT.format(pscore);
        }

        // 如果新增的作者是第一作者的话，要判断是否已经有第一作者
        if ("第一作者".equals(awardAuthor.getAuthortype())) {
            for (Awardauthor author : awardAuthorList) {
                if ("第一作者".equals(author.getAuthortype())) {
                    throw new BaseException("该成果已存在第一作者!");
                }
            }
        }
        awardAuthor.setPscore(Pscore);

        save(awardAuthor);

        // 维护AllAuthor字段
        updateAllAuthor(award, awardAuthor);

        return true;
    }

    /**
     * 删除奖励成果作者
     * @param id
     * @return
     */
    @Override
    public boolean deleteAwardAuthor(String id) {
        Awardauthor awardAuthor = super.getOne(Wrappers.lambdaQuery(Awardauthor.class)
                .eq(Awardauthor::getAwardAuthorID, id));
        Award award = iAwardService.query().eq("AwardID", awardAuthor.getAwardID()).one();
        checkRoleUtil.checkPermissionAchievement(award.getStatus());

        boolean result = baseMapper.deleteById(awardAuthor) == 1;

        // 维护AllAuthor字段
        if (result) {
            updateAllAuthor(award, awardAuthor);
        }

        return result;
    }

    /**
     * 修改奖励成果作者
     * @param awardAuthor
     * @return
     */
    @Override
    public boolean updateAwardAuthor(Awardauthor awardAuthor) {
        Award award = iAwardService.query().eq("AwardID", awardAuthor.getAwardID()).one();
        checkRoleUtil.checkPermissionAchievement(award.getStatus());
        double newAssessment;
        try {
            String assessment = awardAuthor.getAssessment();
            // 如果考核系数为null或空，默认为0
            if (assessment == null || assessment.trim().isEmpty()) {
                newAssessment = 0.0;
            } else {
                newAssessment = Double.parseDouble(assessment);
            }
        } catch (NumberFormatException e) {
            throw new BaseException("考核系数格式不正确");
        }
        if (newAssessment > 100 || newAssessment < 0) {
            throw new BaseException("输入数据应在0-100范围内");
        }

        // 查询该成果的所有作者
        List<Awardauthor> awardAuthorList = query().eq("AwardID", awardAuthor.getAwardID()).list();

        double sum = 0;
        // 只计算已填写考核系数的作者（排除当前修改的作者）
        for (Awardauthor author : awardAuthorList) {
            if (!author.getAwardAuthorID().equals(awardAuthor.getAwardAuthorID())) {
                if(!StrUtil.isBlank(author.getAssessment())){
                    sum += Double.parseDouble(author.getAssessment());
                }
            }
        }
        // 检查已填写考核系数的总和是否超过100
        if (sum + newAssessment > 100) {
            throw new BaseException("已填写作者考核系数总和大于100");
        }

        String Pscore = "0.00";

        LambdaQueryWrapper<Award_Qualification> wrapper = Wrappers.lambdaQuery(Award_Qualification.class)
                .eq(Award_Qualification::getAwardID, awardAuthor.getAwardID());
        Award_Qualification awardQualification= iAwardQualificationService.getOne(wrapper);

        if(awardQualification != null){
            int finalValue = (int) awardQualification.getFinalValue();
            // 计算并保留两位小数
            double pscore = finalValue * newAssessment / 100.0;
            Pscore = DECIMAL_FORMAT.format(pscore);
        }
        awardAuthor.setPscore(Pscore);
        boolean result = baseMapper.updateById(awardAuthor) == 1;

        // 维护AllAuthor字段
        if (result) {
            updateAllAuthor(award, awardAuthor);
        }

        return result;
    }

    /**
     * 查询奖励成果的作者列表
     * @param id 成果ID
     * @return 作者列表
     */
    @Override
    public List<Awardauthor> listAuthor(String id) {
        List<Awardauthor> list = baseMapper.selectList(Wrappers.lambdaQuery(Awardauthor.class)
                .eq(Awardauthor::getAwardID, id));

        list.sort(Comparator.comparingInt(p -> AUTHOR_TYPE_ORDER.indexOf(p.getAuthortype())));
        return list;
    }



    /**
     * 维护AllAuthor字段
     * @param award
     * @param awardAuthor
     */
    private void updateAllAuthor(Award award, Awardauthor awardAuthor) {
        // 1. 先清空原来的AllAuthor字段
        award.setAllAuthor(null);
        iAwardService.updateById(award);

        // 2. 查询该成果的所有作者
        List<Awardauthor> allAuthorList = iAwardauthorService.listAuthor(awardAuthor.getAwardID());

        // 3. 按照作者类型排序
        allAuthorList.sort(Comparator.comparingInt(p -> AUTHOR_TYPE_ORDER.indexOf(p.getAuthortype())));

        // 4. 获取用户主键ID
        List<String> userAccountList = allAuthorList.stream()
                .map(Awardauthor::getUserAccount)
                .collect(Collectors.toList());

        List<User> userList = Collections.emptyList();
        if (!userAccountList.isEmpty()) {
            userList = iUserService.list(Wrappers.lambdaQuery(User.class)
                    .in(User::getAccount, userAccountList));
        }

        List<String> uidList = userList.stream()
                .map(User::getUid)
                .collect(Collectors.toList());

        // 5. 拼接字符串
        String allAuthor = String.join(",", uidList);

        // 6. 更新AllAuthor字段
        award.setAllAuthor(allAuthor);
        iAwardService.updateById(award);
    }
}
